package utils

import (
	"fmt"
	"github.com/hashicorp/consul/api"
)

type Client struct {
	client *api.Client
}

type ConsulRegister struct {
	Id      string
	Name    string
	Tags    []string
	Address string
	Port    int
}

func NewConsul(host string, port int) *Client {
	config := api.DefaultConfig()
	config.Address = fmt.Sprintf("%v:%v", host, port)
	client, err := api.NewClient(config)
	if err != nil {
		return nil
	}
	return &Client{client: client}
}

func (c *Client) Register(register ConsulRegister) error {
	a := new(api.AgentServiceRegistration)
	a.ID = register.Id
	a.Name = register.Name
	a.Tags = register.Tags
	a.Address = register.Address
	a.Port = register.Port
	err := c.client.Agent().ServiceRegister(a)
	if err != nil {
		return err
	}
	return err
}

func (c *Client) DeRegister(id string) error {
	err := c.client.Agent().ServiceDeregister(id)
	return err
}

func (c *Client) Service() map[string]*api.AgentService {
	services, err := c.client.Agent().Services()
	if err != nil {
		return nil
	}
	return services
}

//type Client struct {
//	client *api.Client
//}
//type ConsulRegister struct {
//	Id      string
//	Name    string
//	Tags    []string
//	Address string
//	Port    int
//}
//
//func NewConsul(host string, port int) *Client {
//	config := api.DefaultConfig()
//	config.Address = fmt.Sprintf("%v:%v", host, port)
//	client, err := api.NewClient(config)
//	if err != nil {
//		return nil
//	}
//	return &Client{client: client}
//}
//
//func (c *Client) Register(register ConsulRegister) error {
//	a := new(api.AgentServiceRegistration)
//	a.ID = register.Id
//	a.Name = register.Name
//	a.Tags = register.Tags
//	a.Tags = register.Tags
//	a.Address = register.Address
//	a.Port = register.Port
//
//	err := c.client.Agent().ServiceRegister(a)
//
//	return err
//}
//type Client struct {
//	client *api.Client
//}
//
//type ConsulRegister struct {
//	Id      string
//	Name    string
//	Tags    []string
//	Address string
//	Port    int
//}
//
//func NewConsulClient(host string, port int) *Client {
//	config := api.DefaultConfig()
//	config.Address = fmt.Sprintf("%v:%v", host, port)
//	client, err := api.NewClient(config)
//	if err != nil {
//		return nil
//	}
//	return &Client{client: client}
//}
//

//func (c *Client) Register(register ConsulRegister) error {
//	a := new(api.AgentServiceRegistration)
//	a.ID = register.Id
//	a.Name = register.Name
//	a.Tags = register.Tags
//	a.Address = register.Address
//	a.Port = register.Port
//	err := c.client.Agent().ServiceRegister(a)
//	return err
//}
